<template>
	<u-navbar title="手动要货" bgColor="#FBFBFF" :autoBack="true" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
		<template #right>
			<view class="navbar-submit" @click="submit">
				<text>提交</text>
			</view>
		</template>
	</u-navbar>
	<view class="baseForm">
		<u--form labelPosition="left" :model="umodel" :rules="rules" ref="uForm" labelWidth="160rpx" errorType="toast">
			<u-form-item label="扫描包装条码">
				<!-- 条码录入 -->
				<scan-bar ref="scanBarRef" @code-scanned="getScanResult" class="scan-bar"></scan-bar>
			</u-form-item>
			<u-form-item label="物料" prop="name" borderBottom>
				<u--input v-model="umodel.name"></u--input>
			</u-form-item>
			<u-form-item label="生产线" prop="produceLineCode" borderBottom @click="openproduceLineCodeelect">
				<u--input v-model="umodel.produceLineCode" disabled disabledColor="#ffffff" inputAlign="right"
					placeholder="请选择生产线"></u--input>
				<template #right>
					<u-icon name="arrow-right"></u-icon>
				</template>
			</u-form-item>
			<u-form-item label="数量" prop="requestQuantity">
				<u-number-box v-model="umodel.requestQuantity" :min="1" integer></u-number-box>
			</u-form-item>
		</u--form>
		<!-- 搜索信息 -->
		<view class="search">
			<u-button text="重置" class="custom-style" @click="reset"></u-button>
			<u-button type="primary" text="添加" class="custom-style" :loading="addLoading" @click="addList"></u-button>
		</view>
		<u-line></u-line>
		<!-- 卡片显示 -->
		<view v-if="scanList.length" class="list">
			<text class="list-title">列表信息({{ scanList.length }})</text>
			<view class="card" v-for="item in scanList" :key="item.code">
				<view class="right">
					<view class="title">
						生产线：{{ item.produceLineCode }}
						<br>
						物料号：{{ item.name}}
					</view>
					
				</view>
				<view class="left">
				
					<view class="number">
						{{ item.requestQuantity }}
					</view>
				</view>
				<view class="delete" @click="deleteItem(item)">
					<u-icon name="删除" color="#999" size="16px"></u-icon>
				</view>
			</view>
		</view>
		<view v-else>
			<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
		</view>
	</view>
	<u-picker :show="show" :columns="columns" title="请选择" keyName="lineName" immediateChange cancel-text="取 消"
		@cancel="show = false" @confirm="produceLineCodeelect"></u-picker>
	<u-back-top :scroll-top="scrollTop" top="200" mode="squery"></u-back-top>
</template>

<script lang="ts" setup>
	import { ref, reactive } from 'vue';
	import { onPageScroll } from '@dcloudio/uni-app';
	import ScanBar from '@/components/scan-bar/index.vue';
	import { http } from '@/utils/http';
	import { PageResult } from '@/produceLineCode/type';
	import { useDictionaryStore } from "@/stores/useDictionaryStore";
	// 获取安全距离高度
	const { safeAreaInsets } = uni.getSystemInfoSync();

	// 监听页面到顶部距离
	const scrollTop = ref(0)
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop
	})

	// 表单数据定义
	const umodel = reactive({
		dropdownShow: true,
		searchSuggestions: ['apple', 'banana', 'cherry', 'date', 'elderberry'],
		id: '',
		code: '',
		name: '',
		storageUnitId: '',
		storageUnitCode: '',
		extenalCode: '',
		searchText: '',
		produceLineCode: '',
		lines: [],
		materials: [],
		requestQuantity: 1,
		materialId: '',
		materialCode: '',
		materialName: '',
		requestCode: '',
		organizationId: '',
		organizationCode: '',
		organizationName: '',
		plantId: '',
		plantCode: '',
		plantName: '',
		workStationCode: '',
		storageLocationId: '',
		storageLocationCode: '',
		storageLocationName: '',
		warehouseId: '',
		warehouseCode: '',
		warehouseName: '',
		storageTypeId: '',
		storageTypeCode: '',
		storageTypeName: '',
		storageSectionId: '',
		storageSectionCode: '',
		binId: '',
		binCode: '',
		quantityUnit: '',
		transferPriority: '',
		requestState: '',
		requestSource: 1,
		prepareTime: '',
		receiveTime: '',
		version: '',
		remarks: '',
		createdUserName: '',
		lastUpdatedUserName: '',
		deleted: '',
	});

	// 表单规则定义
	const rules = ref({
		name: [
			{
				type: 'string',
				required: true,
				message: '请填写物料名称',
				trigger: ['change']
			},
			{
				type: 'string',
				max: 40,
				message: '物料名称不超过40个字符',
				trigger: ['change']
			}
		],
		produceLineCode: {
			type: 'string',
			required: true,
			message: '请选择生产线',
			trigger: ['blur', 'change']
		}
	});
	const show = ref(false);
	const columns = ref([]);
	function produceLineCodeelect(e) {
		if (e.value.length) {
			umodel.produceLineCode = e.value[0].lineCode;
		}
		show.value = false
	}
	function openproduceLineCodeelect() {
		show.value = true;
		uni.hideKeyboard();
	}
	// 定义列表数据
	const scanList = ref([])

	// 重置表单
	const uForm = ref();
	const scanBarRef = ref();

	function reset() {
		uForm.value.resetFields();
		scanBarRef.value.reset();
	}
	getLines('ddf3c7ec594d4421ad82ce2d99fc3f58');
	getMaterials('100001000');
	function deleteItem(item) {
		// 从数组中找到对应的项的索引
		const index = this.scanList.findIndex(i => i.code === item.code);
		// 如果找到了对应的索引
		if (index !== -1) {
			// 使用 splice 方法删除对应的项
			this.scanList.splice(index, 1);
		}
	}
	// 添加一条
	const addLoading = ref(false);
	function addList() {
		if (umodel.name) {
			uForm.value.validate().then((res) => {
				addLoading.value = true;
				// 模拟添加数据操作
				setTimeout(() => {
					const obj = JSON.parse(JSON.stringify(umodel))
					scanList.value.push(obj)
					console.log(obj)
					console.log(scanList.value)
					addLoading.value = false;
					uni.showToast({
						title: '添加成功',
					})
					reset()
				}, 1000)
			});
		} else {
			uni.showToast({
				title: '请先录入物料号',
				icon: 'none'
			})
		}
	}
	async function getLines(organizationId) {
		try {
			const result : PageResult<any> = await http({
				method: 'GET',
				url: '/wms/produceline/getList',
				data: {
					organizationId: organizationId
				},
			})
			umodel.lines = result.data;
			columns.value = [umodel.lines]
			console.log('columns', columns.value);
		} catch (error) {
			console.error('获取生产线失败', error);
		}
	}
	async function getMaterials(Code : string) {
		try {
			const result : PageResult<any> = await http({
				method: 'GET',
				url: '/wms/material/getbycode/' + Code,
				data: {

				}
			})
			console.log(result.data);
		} catch (error) {
			console.error('获取物料失败', error);
		}
	}
	// 获取扫码结果
	async function getScanResult(code : string) {
		if (code) {
			try {
				const result : PageResult<any> = await http({
					method: 'GET',
					url: '/wms/storageunit/get/' + code,
					data: {

					}
				})
				umodel.materialId = result.data.materialId;
				umodel.materialCode = result.data.materialCode;
				umodel.materialName = result.data.materialName;
				umodel.name = result.data.materialCode + '|' + result.data.materialName;
				umodel.storageLocationId=result.data.storageLocationId;
				umodel.storageLocationCode=result.data.storageLocationCode;
				umodel.storageLocationName=result.data.storageLocationName;
			} catch (error) {
				console.error(error);
			}
		} else {
			umodel.name = '';
		}
		umodel.code = code;
	}
	// 表单提交
	const posting = ref(false);
	function submit() {
		if (posting.value === false) {
			if (scanList.value.length === 0) {
				uni.showToast({
					title: '请添加要货信息',
					icon: 'none'
				});
				return;
			}
			uni.showLoading({
				title: '提交中···'
			})
			posting.value = true;
			console.log(scanList.value[0].requestQuantity)
		
				http({
					url: '/wms/lesproducematerialrequest/request',
					method: 'POST',
					data: scanList.value
				})
			
			posting.value = false;
			uForm.value.resetFields();
			uni.hideLoading();
			uni.showToast({
				title: '已成功'
			})
			scanList.value = [];
		}
	}
</script>

<style lang="scss" scoped>
	.baseForm {
		padding: $uni-page-padding;
		padding-bottom: 30px;
		margin: 50px 0 0 0;

		.u-form {
			margin-top: 5px;

			:deep(.u-form-item__body) {
				padding: 5px 0;
			}

			.u-input {
				border: 1px solid $uni-input-border-color;
			}

			.scan-bar {
				display: flex;
				flex: 1;
			}
		}

		.u-line {
			padding: 10px 0;
		}

		.search {
			display: flex;

			.custom-style {
				// width: 120px;
				margin: 10px 5px 5px;
				height: 36px;
				border-radius: 8px;

				&:nth-child(1) {
					flex: 1
				}

				&:nth-child(2) {
					flex: 3
				}
			}
		}

		.list {
			.list-title {
				line-height: 40px;
				font-size: 14px;
				color: rgba(0, 0, 0, 0.4);
			}

			.card {
				margin-top: 5px;
				margin-bottom: 10px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				padding: 10px 0;
				transition: all 300ms ease;
				box-shadow: 0 0 1px rgba(0, 0, 0, 0.1);

				.left {
					// flex-basis: 90rpx;
					padding-right: 10px;
					text-align: right;
					font-size: 13px;

					.enter {
						line-height: 20px;
						margin-bottom: 5px;
					}

					.number {
						font-size: 13px;
						line-height: 18px;
					}

					:deep(.u-icon--right) {
						flex-direction: row-reverse;
					}
				}

				.right {
					flex: 1;
					padding-left: 15px;

					.title {
						font-size: 15px;
						line-height: 20px;
						margin-bottom: 5px;
					}

					.body {
						color: rgba(0, 0, 0, 0.4);
						font-size: 13px;
						line-height: 18px;
					}
				}
			}
		}
	}
</style>